<script lang="ts" setup>
import DataTable from "@/components/data-table/index.vue";
import {h, onMounted, reactive, ref} from "vue";
import router from '@/router'
import {ElAlert, ElButton, ElLoading, ElMessage, ElMessageBox, ElScrollbar, ElRadioGroup, ElRadio} from "element-plus";
import {env, service} from "@/utils";
import EditProcess from './edit-process.vue'

const tableRef = ref<InstanceType<typeof DataTable>>()
const editProcessRef = ref<InstanceType<typeof EditProcess>>()
const props = defineProps({
    owner: {
        type: String,
        required: true
    },
    sessionId: {
        type: String,
        required: true
    },
    sessions: {
        type: Array<any>
    }
})

const params = ref({
    sessionId: props.sessionId
})
const columns = ref([
    { prop: 'title', label: '标题', width: 250, tooltip: true},
    { prop: 'name', label: '进程标识', minWidth: 400, tooltip: true},
    { prop: 'position', label: '文件位置', width: 350, tooltip: true},
    { prop: 'startup', label: '启动命令', width: 250, tooltip: true, visible: false},
    { prop: 'shutdown', label: '关闭命令', width: 250, tooltip: true, visible: false},
    { prop: 'uri', label: '访问地址', width: 200, tooltip: true,
        render: ({row}: any) => {
            if (row.uri) {
                return h(ElButton, {link: true, tag: 'a', type: 'primary', onClick: () => toComponent(row)}, {default: () => row.uri})
            }
        }
    },
    {
        type: "action", width: 250, maxCollapseButtons: 2,
        render: [
            {label: '编辑', icon: 'el-icon-edit-pen', onClick: ({row}: any)=> onEditProcess('update', row)},
            {label: '删除', icon: 'el-icon-delete', onClick: ({row}: any)=> onDeleteProcess(row), type: 'danger'},
            {label: '复制', icon: 'el-icon-copy-document', onClick: ({row}: any)=> onEditProcess('copy', row)},
            {label: '启动', icon: 'el-icon-switch-button', onClick: ({row}: any)=> onCommand('startup', row)},
            {label: '关闭', icon: 'el-icon-close', onClick: ({row}: any)=> onCommand('shutdown', row)},
            {label: '状态', icon: 'el-icon-notification', onClick: ({row}: any)=> onCommand('status', row)},
        ]
    },
])

const connecting = ref(false);
const onTestConnection = () => {
    connecting.value = true;
    if (env.APP_VERSION === '3.0.0') {
        service.post('/ssh/test', {sessionId: params.value.sessionId}, {timeout: 30000}).then(() => ({})).finally(() => connecting.value = false)
    } else {
        service.get('/ssh/test', {sessionId: params.value.sessionId}).then(() => ({})).finally(() => connecting.value = false)
    }
}

const onEditProcess = (operate:string, data?:any) => {
    let form;
    if (operate === 'update') {
        form = {...data};
    } else if (operate === 'copy') {
        form = {...data};
        form.id = null;
    }
    editProcessRef.value?.open({
        data: form,
        type: operate === 'update'? 'put':'post',
        confirm: (resolve: (value: any)=> void, form: any, operate: AxiosMethod) => {
            form.name = form.name.join(';')
            service[operate]('/ssh/process', form).then(({code}) => {
                if (code === 200) {
                    tableRef.value?.refresh()
                }
                resolve(code);
            })
        },
    })
}

const onDeleteProcess = (data: any) => {
    service.confirm(`确定删除${data.title}进程信息?`, {
        url: '/ssh/process',
        data: {id: data.id},
        success: tableRef.value?.refresh
    })
}

const onCommand = (type:string, data?: any) => {
    if (data) {
        ElMessageBox.confirm(`确定执行[${data === 'startup' ? '开始' : data === 'shutdown' ? '关闭' : '状态'}]指令?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            const text = ref("Loading(29s)...")
            const loadingInstance = ElLoading.service({
                lock: true,
                text: text
            })
            let seconds = 29;
            const interval = setInterval(function() {
                if (seconds === 0) {
                    clearInterval(interval);
                } else {
                    seconds--;
                    text.value = 'Loading(' + seconds + 's)...';
                }
            }, 1000);
            service.post('/ssh/execute', {type: type, ids: data.id}, {timeout: 30000}).then(({code, data}) =>  {
                if (code === 200) {
                    let children: Array<any> = [];
                    data.forEach((item: any) => {
                        item['closable'] = false
                        item['class'] = 'alert-command'
                        children.push(h(ElAlert, item))
                    })
                    ElMessageBox({
                        title: '执行结果',
                        showConfirmButton: false,
                        customClass: 'message-box__command',
                        message: h(ElScrollbar, {maxHeight: '60vh'}, {default: ()=> children}),
                    })
                }
            }).finally(() => {
                clearInterval(interval);
                loadingInstance.close();
            })
        });
    } else {
        ElMessage.warning("请先选择进程信息")
    }
}

const toComponent = (data: any) => {
    if (data.mode === 'API') {
        const checked = ref<string>('Zookeeper')
        if (data.title.toLowerCase().indexOf('hadoop') > -1 || data.title.toLowerCase().indexOf('hdfs') > -1){
            checked.value = 'Hadoop'
        }
        ElMessageBox({
            title: '选择组件',
            confirmButtonText: '进入',
            message: () =>{
                return h(ElRadioGroup, {
                    modelValue: checked.value,
                    'onUpdate:modelValue': (val: string) => {
                        checked.value = val
                    },
                }, {
                    default: () => {
                        return [
                            h(ElRadio, {value:"Zookeeper"}, {default: () => 'Zookeeper'}),
                            h(ElRadio, {value:"Hadoop"}, {default: () => 'Hadoop'}),
                        ]
                    }
                })
            },
        }).then(() => {
            const {href} = router.resolve({name: checked.value, query: {uid: data.uriId}});
            window.open(href, "_blank");
        }).catch(()=>({}))

    } else {
        window.open(data.uri, "_blank");
    }
}
</script>

<template>
    <div style="height: calc(100vh - 134px);">
        <data-table ref="tableRef" api="/ssh/process" :params="params" :columns="columns" :pagination="false">
            <template #button>
                <el-button icon="el-icon-plus" @click="onEditProcess('create')">新增</el-button>
                <el-button icon="el-icon-connection" @click="onTestConnection()" :loading="connecting">测试连接</el-button>
            </template>
        </data-table>
    </div>
    <edit-process ref="editProcessRef" :sessions="sessions" :session-id="params.sessionId" :owner="owner"/>
</template>

<style>

.message-box__command {
    width: 65% ;
    max-width: unset;
}

.alert-command {
    white-space: pre-wrap;
}
</style>